package com.vivimice.lotroller.demo;

import com.vivimice.lotroller.annotation.ListenAt;
import com.vivimice.lotroller.notification.NotificationAgent;
import com.vivimice.lotroller.notification.NotificationType;
import com.vivimice.lotroller.utils.NotificationUtils;

/**
 * Networking behaviour emulator
 * 
 * @author vivimice
 */
public class DemoFileSystemEmulator {

	// Incoming notifications
	public static NotificationType ASYNC_LOAD_RESOURCES;

	// Outgoing notifications
	public static NotificationType RESOURCES_LOADED;

	private NotificationAgent agent;
	
	private Thread asyncLoadThread = new Thread(new Runnable() {
		@Override
		public void run() {
			// just some dummy job
			Object resources = null;
			System.out.println("Start loading resources ...");
			try {
				// loading may take some time
				Thread.sleep((long) (Math.random() * 8000 + 2000));
				resources = "This is a resource";
			} catch (InterruptedException e) {}
			System.out.println("Resources loaded.");
			
			// Sending out notification
			agent.sendNotification(RESOURCES_LOADED, resources);
		}
	});

	static {
		// auto name each declared NotificationType
		// for example:
		// LOAD_USER will be auto assigned a name as
		// "TestNetworkingEmulator.LOAD_USER"
		// this will be very useful while debugging
		NotificationType.doAutoNaming(DemoFileSystemEmulator.class);
	}

	public DemoFileSystemEmulator(NotificationAgent agent) {
		this.agent = agent;
		// auto associate notification type
		NotificationUtils.associateListeners(agent, this);
	}

	@ListenAt({ "ASYNC_LOAD_RESOURCES" })
	public void loadUser() {
		// doing some job
		asyncLoadThread.start();
	}

	public void join() throws InterruptedException {
		asyncLoadThread.join();
	}

}
